package de.tapps.brainstorming;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;

import android.content.Context;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
/**
 * Adds a new topic with HTTP POST Request to a specified PHP Script which
 * puts the data to a MYSQL Database
 * 
 * @author Timo
 * Encrypted - ok
 */
public class CreateTopic extends AsyncTask<String, Integer, String> {
		String topic;
		String content;
		String publisher;
		private MainActivity activity = new MainActivity();
		private Storage storage;
private Crypter crypter;
		public CreateTopic(MainActivity act,String pTopic, String pContent, String pPublisher) {
			topic = pTopic;
			content = pContent;
			publisher = pPublisher;
			activity = act;
			crypter = new Crypter(activity);
			storage = new Storage(activity);

		}

		@Override
		protected String doInBackground(String... arg0) {
			new Thread(new Runnable() {
				public void run() {
					// Create a new HttpClient and Post Header
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(
							"http://t-apps-online.de/BrainStorming/addNewTopic.php");
					try {
						TelephonyManager telephonyManager = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
						String imei = telephonyManager.getDeviceId();
						List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
								2);
						
						nameValuePairs.add(new BasicNameValuePair("content", 
								crypter.encrypt(content)));
						nameValuePairs.add(new BasicNameValuePair("topic",
								crypter.encrypt(topic)));
						nameValuePairs.add(new BasicNameValuePair("lang",
								storage.getLanguage()));
						nameValuePairs
								.add(new BasicNameValuePair("imei", crypter.encrypt(imei)));
						httppost.setEntity(new UrlEncodedFormEntity(
								nameValuePairs));
						// Execute HTTP Post Request
						HttpResponse response = httpclient.execute(httppost);
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
					} catch (IOException e) {
						// TODO Auto-generated catch block
					}
				}
			}).start();
			return null;
		}
	}